package cn.wgoodq.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.UUID;

/**
 * 本监视器负责记录系统对每个前台请求的响应时间。
 * Created by Kyou on 2017/4/15.
 */
// AOP切面
@Aspect
// 本监视器最优先启动
@Order(1)
@Component
public class WebAccessMonitor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 拦截.
     * 解释下：
     * <p>
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 定义在web包或者子包
     * ~ 第三个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
    @Pointcut("execution(* cn.wgoodq.controller..*.*(..))")
    void webControllerPoint() {
    }

    @Around("webControllerPoint()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

        // 开始计时
        long startTime = System.currentTimeMillis();

        // 记录请求信息
        String uuid = writeAccessLog(joinPoint);

        // 处理请求
        Object rst = joinPoint.proceed();

        // 结束计时并记录处理结果和请求用时
        logger.debug("uuid:{}; result:{}; used {} ms", uuid, rst.toString(), System.currentTimeMillis() - startTime);

        return rst;
    }

    /**
     * 记录请求信息
     *
     * @param joinPoint In Spring AOP, a join point always represents a method execution.
     * @return 本次请求的编号
     */
    private String writeAccessLog(ProceedingJoinPoint joinPoint) {
        // 获取HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String uuid = UUID.randomUUID().toString();

        // 记录下请求内容
        logger.debug("uuid:" + uuid +
                "; URL:" + request.getRequestURL().toString() +
                "; HTTP_METHOD:" + request.getMethod() +
                "; REMOTE_IP:" + request.getRemoteAddr() +
                "; ARGS:" + Arrays.toString(joinPoint.getArgs()));
        return uuid;
    }
}
